package Reference;

import java.util.HashMap;
import java.util.WeakHashMap;

/**
 * @Author: dch
 * @Date: 2020/5/18 13:56
 * @Description: 引用队列
 * 对于虚引用PhantomReference必须和引用队列（ReferenceQueue）联合使用，
 * 即虚引用PhantomReference在被回收之前会被引用队列（ReferenceQueue）保存下来。
 */
public class WeakHashMapDemo {
    public static void main(String[] args) {
        myHashMap();
        System.out.println("=====================");
        myWeakHashMap();
    }

    private static void myHashMap() {
        HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
        Integer key = new Integer(1);
        String value = "HashMap";

        hashMap.put(key,value);
        System.out.println(hashMap);

        key = null;
        System.out.println(hashMap);

        System.gc();
        System.out.println(hashMap);
    }

    private static void myWeakHashMap() {
        WeakHashMap<Integer,String> weakHashMap = new WeakHashMap<Integer,String>();
        Integer key = new Integer(2);
        String value = "WeakHashMap";

        weakHashMap.put(key,value);
        System.out.println(weakHashMap);

        key = null;
        System.out.println(weakHashMap);

        System.gc();
        System.out.println(weakHashMap);
    }
}
